package com.dsunsoft.rtu.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.dsunsoft.rtu.entity.Subject;
import com.dsunsoft.rtu.service.ToolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/api/tool")
public class ToolController {


    @Autowired
    private ToolService toolService;

    @GetMapping(value = "/hellow")
    public String pdfToExcel(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        return "你好";
    }

    @PostMapping(value = "/txtToExcel")
    public void txtToExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        List<Subject> list = toolService.pdfToExcel(file);
        log.info("题目行数：" + list.size());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String fileName = "subject-" + sdf.format(new Date())+ ".xlsx";
//        Map<String, Object> map = new HashMap<>();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        ClassPathResource classPathResource = new ClassPathResource("files/subject.xlsx");
        InputStream in = ToolController.class.getClassLoader().getResourceAsStream("files/subject.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(in).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build();
        excelWriter.fill(new FillWrapper("data1", list), fillConfig, writeSheet);
//        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }
}
